﻿package com.toncen.samepms.system.action;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.json.simple.JSONObject;

import com.toncen.samepms.basic.dao.UserDao;
import com.toncen.samepms.basic.domain.User;
import com.toncen.samepms.common.AbstractDatabaseAction;
import com.toncen.samepms.interceptor.Begin;
import com.toncen.samepms.interceptor.In;
import com.toncen.samepms.interceptor.Out;
import com.toncen.samepms.system.dao.MessageDao;
import com.toncen.samepms.system.domain.Message;
import com.opensymphony.xwork2.ActionContext;
import com.sky.common.date.DateTools;
import com.sky.common.json.JSONUtils;

/**
 * 描述：系统消息表SYSTEM_MESSAGE的action文件
 * 
 * @author zq
 * 
 */
public class MessageAction extends AbstractDatabaseAction<Message, MessageDao> {
	/**
	 * 序列号
	 */
	private static final long serialVersionUID = 1331803603555L;

	public MessageAction() throws Exception {
		super();
	}

	// 收件人姓名
	@In
	@Out
	private String reciveNames;

	public String getReciveNames() {
		return reciveNames;
	}

	public void setReciveNames(String reciveNames) {
		this.reciveNames = reciveNames;
	}

	// 收件人集合
	@In
	@Out
	private List<User> reciveUserList = new ArrayList<User>(5);

	public List<User> getReciveUserList() {
		return reciveUserList;
	}

	public void setReciveUserList(List<User> reciveUserList) {
		this.reciveUserList = reciveUserList;
	}

	/**
	 * 
	 * TODO 更新消息状态
	 * 
	 * @author Apr 6, 2012 3:31:53 PM ZQ
	 * @throws Exception
	 * 
	 */
	public void onDoCheckMessage() throws Exception {
		int hasRead = getDomain().getHasRead();
		// 消息未读，
		if (hasRead == 0) {
			// 签收消息
			getDomain().setHasRead(1);
			getDao().update(getDomain());
		}
	}

	@Override
	public void prepareOnDoEdit() throws Exception {
		super.prepareOnDoEdit();
		// 初始化收件人信息
		this.reciveUserList = getDomain().getReceiveUserList();
		// onDoCheckMessage();
	}

	@Override
	public void prepareOnDoNew() throws Exception {
		super.prepareOnDoNew();
		// // 发送人为当前用户
		// HttpServletRequest request = ServletActionContext.getRequest();
		// // 接收人从列表传进来
		// this.reciveNames = MyRequest.getString(request, "reciveNames",
		// "接收人");
		// 初始化接收人信息
		UserDao userDao = new UserDao();
		this.reciveUserList = userDao.getByIds(getDomain().getReceiver());
		User user = getCurrentUser();
		getDomain().setSender(user);
		getDomain().setType(0);
		// 今天
		Date today = new Date();
		getDomain().setStartTime(today);
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(today);
		calendar.add(Calendar.DAY_OF_MONTH, 7);
		// 结束时间默认为开始时间+7天
		getDomain().setEndTime(calendar.getTime());
	}

	@Override
	public void prepareOnDoView() throws Exception {
		super.prepareOnDoView();
		// 初始化收件人信息
		this.reciveUserList = getDomain().getReceiveUserList();
		// 初始化收件人姓名
		// setReciveNames(getReciveName(reciveList));

		onDoCheckMessage();
	}

	/**
	 * 
	 * 取接收人姓名
	 * 
	 * @author Mar 16, 2012 2:01:18 PM ZQ
	 * @param list
	 * @return
	 * 
	 */
	private String getReciveName(List<User> list) {
		List<String> nameList = new ArrayList<String>();
		if (null != list) {
			for (User user : list) {
				nameList.add(user.getName());
			}
		}
		return nameList.toString();
	}

	/**
	 * 
	 * TODO 接收消息
	 * 
	 * @author Mar 21, 2012 3:16:48 PM ZQ
	 * @return
	 * @throws Exception
	 * 
	 */
	@Begin
	public String onDoGet() throws Exception {
		logger.debug("执行【onDoGet】...");
		prepareOnDoList();
		return SUCCESS;
	}

	/**
	 * 
	 * TODO 发送消息
	 * 
	 * @author Mar 21, 2012 3:17:18 PM ZQ
	 * @return
	 * @throws Exception
	 * 
	 */
	@Begin
	public String onDoSend() throws Exception {
		logger.debug("执行【onDoSend】...");
		prepareOnDoList();
		return SUCCESS;
	}

	/**
	 * 
	 * TODO 显示系统消息
	 * 
	 * @author Apr 19, 2012 4:27:59 PM ZQ
	 * @throws Exception
	 * 
	 */
	public void onDoGetNewMessage() throws Exception {
		ActionContext ctx = ActionContext.getContext();
		// HttpServletRequest request = (HttpServletRequest)
		// ctx.get(ServletActionContext.HTTP_REQUEST);
		Vector<Map<String, Object>> v = new Vector<Map<String, Object>>();
		HttpServletResponse response = (HttpServletResponse) ctx.get(ServletActionContext.HTTP_RESPONSE);
		// 当前用户
		User user = getCurrentUser();
		// 配置的消息条数
		String row = getConfigValue("new_message_row");
		// 请求参数
		Map<String, Object> parMap = new HashMap<String, Object>();
		parMap.put("userId", user.getId());
		parMap.put("row", row);
		List<Message> messageList = getDao().getNewMessage(parMap);

		// 组装消息对象json
		Map<String, Object> msgMap = null;
		for (Message message : messageList) {
			msgMap = new HashMap<String, Object>();
			msgMap.put("id", message.getId());
			msgMap.put("title", message.getTitle());
			msgMap.put("systemContent", message.getContent());
			msgMap.put("url", message.getTargetUrl());
			v.add(msgMap);
		}
		response.getWriter().println(JSONUtils.object2JSON(v));
		response.getWriter().flush();
		response.getWriter().close();
	}

	/**
	 * 
	 * TODO 返回用户未读消息,给其它客户端
	 * 
	 * 
	 * 
	 * @author Jul 3, 2013 2:45:38 PM ZQ
	 * @throws Exception
	 * 
	 */
	public void onDoGetNewMessageToAndroid() throws Exception {
		ActionContext ctx = ActionContext.getContext();
		HttpServletRequest request = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ctx.get(ServletActionContext.HTTP_RESPONSE);

		Map<String, Object> msgMap = null;

		String userName = String.valueOf(request.getParameter("userName"));
		String passWord = String.valueOf(request.getParameter("passWord"));
		/**
		 * type=1:验证用户
		 */
		String type = String.valueOf(request.getParameter("type"));
		UserDao userDao = new UserDao();
		List<User> list = userDao.getByAccount(userName);
		User user = null;
		if (!list.isEmpty()) {
			user = list.get(0);
		}
		Vector<Map<String, Object>> v = new Vector<Map<String, Object>>();
		if (user != null && passWord.equals(user.getOriginalPassword())) {
			if (type.equals("1")) {
				// 验证用户名密码
				msgMap = new HashMap<String, Object>();
				msgMap.put("count", 0);
				msgMap.put("success", "1");
				msgMap.put("error", "验证成功");
			} else {
				// 请求参数
				Map<String, Object> parMap = new HashMap<String, Object>();
				parMap.put("userId", user.getId());
				List<Message> messageList = getDao().getNewMessageForAndroid(parMap);

				// 系统名称
				String systemName = getConfigValue("system_title");

				// 组装消息对象json
				for (Message message : messageList) {
					msgMap = new HashMap<String, Object>();
					msgMap.put("systemName", systemName);
					msgMap.put("title", message.getTitle());
					msgMap.put("content", message.getContent());
					msgMap.put("sendTime", DateTools.getDateTime(message.getSendTime()));
					msgMap.put("sender", message.getSender().getName());

					v.add(msgMap);
				}
				msgMap = new HashMap<String, Object>();
				msgMap.put("count", messageList.size());
				msgMap.put("success", "1");
				msgMap.put("error", "");
			}

		} else {
			msgMap = new HashMap<String, Object>();
			msgMap.put("count", 0);
			msgMap.put("success", "-1");
			msgMap.put("error", "用户名错误");
			// 用户名或密码不正确
			if (user != null && !passWord.equals(user.getPassword())) {
				msgMap.put("success", "-2");
				msgMap.put("error", "密码错误");
			}

		}
		JSONObject json = new JSONObject();
		json.put("messages", v);
		json.put("result", msgMap);
		response.getWriter().println(json);
		// response.getWriter().println(JSONUtils.object2JSON(v));
		response.getWriter().flush();
		response.getWriter().close();
	}

}
